<template>
  <div class="feedback-process-container">
    <div class="page-header">
      <el-page-header @back="goBack" content="反馈处理详情" />
    </div>

    <el-card class="feedback-card">
      <template #header>
        <div class="card-header">
          <span>反馈信息</span>
        </div>
      </template>

      <el-descriptions :column="1" border>
        <el-descriptions-item label="反馈单号">{{ feedback.feedbackId }}</el-descriptions-item>
        <el-descriptions-item label="用户ID">{{ feedback.userId }}</el-descriptions-item>
        <el-descriptions-item label="用户姓名">{{ feedback.userName }}</el-descriptions-item>
        <el-descriptions-item label="反馈内容">{{ feedback.content }}</el-descriptions-item>
        <el-descriptions-item label="反馈时间">{{ feedback.createdAt }}</el-descriptions-item>
        <el-descriptions-item label="当前状态">
          <el-tag :type="feedback.status === 'pending' ? 'warning' : 'success'">
            {{ feedback.status === 'pending' ? '待处理' : '已处理' }}
          </el-tag>
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <el-card class="processing-card">
      <template #header>
        <div class="card-header">
          <span>处理信息</span>
        </div>
      </template>

      <el-form :model="processingForm" label-width="100px" class="processing-form">
        <el-form-item label="处理结果">
          <el-input
            v-model="processingForm.processingResult"
            type="textarea"
            :rows="4"
            placeholder="请输入处理结果描述"
          />
        </el-form-item>

        <el-form-item label="处理状态">
          <el-radio-group v-model="processingForm.status">
            <el-radio label="pending">待处理</el-radio>
            <el-radio label="processed">已处理</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="updateProcessing">保存处理结果</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="points-card">
      <template #header>
        <div class="card-header">
          <span>用户积分奖励</span>
        </div>
      </template>

      <div class="points-content">
        <p>为反馈用户 {{ feedback.userName }} 增加积分：</p>
        <div class="points-buttons">
          <el-button type="primary" @click="addPoints(5)">+5分</el-button>
          <el-button type="success" @click="addPoints(10)">+10分</el-button>
          <el-button type="warning" @click="addPoints(15)">+15分</el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

const route = useRoute()
const router = useRouter()

// 反馈数据
const feedback = ref({
  feedbackId: '',
  userId: '',
  userName: '',
  content: '',
  createdAt: '',
  status: 'pending'
})

// 处理表单数据
const processingForm = ref({
  processingResult: '',
  status: 'pending'
})

// 处理记录数据
const feedbackProcessing = ref({
  processingId: null,
  feedbackId: null,
  processingResult: '',
  createdAt: null,
  processedAt: null
})

// 格式化日期为后端需要的格式
const formatDateTime = (date) => {
  if (!date) return null
  // 如果是字符串且已经是正确格式，直接返回
  if (typeof date === 'string' && date.includes(' ')) {
    return date
  }
  // 如果是Date对象或其他格式，转换为 yyyy-MM-dd HH:mm:ss 格式
  const d = new Date(date)
  if (isNaN(d.getTime())) return null

  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  const hours = String(d.getHours()).padStart(2, '0')
  const minutes = String(d.getMinutes()).padStart(2, '0')
  const seconds = String(d.getSeconds()).padStart(2, '0')

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 获取反馈处理信息
const getFeedbackProcessing = () => {
  const feedbackId = route.query.feedbackId
  if (!feedbackId) return

  axios.get(BASE_URL + `/api/feedbacks/processing/select/feedback/${feedbackId}`)
    .then(response => {
      if (response.data.state === 2001) {
        const processing = response.data.data
        feedbackProcessing.value = processing
        processingForm.value.processingResult = processing.processingResult || ''
        // 处理状态需要从feedback表中获取
        processingForm.value.status = route.query.status || 'pending'
      } else {
        ElMessage.error(response.data.msg || '获取处理信息失败')
      }
    })
    .catch(error => {
      console.error('获取处理信息失败:', error)
      ElMessage.error('获取处理信息失败: ' + (error.message || '网络错误'))
    })
}

// 更新处理信息
const updateProcessing = () => {
  // 格式化日期
  const createdAtFormatted = feedbackProcessing.value.createdAt || formatDateTime(route.query.createdAt)
  const processedAtFormatted = processingForm.value.status === 'processed'
    ? formatDateTime(new Date())
    : null

  // 构建处理数据
  const processingData = {
    processingId: feedbackProcessing.value.processingId,
    feedbackId: parseInt(route.query.feedbackId),
    processingResult: processingForm.value.processingResult || feedbackProcessing.value.processingResult,
    createdAt: createdAtFormatted,
    processedAt: processedAtFormatted
  }

  // 将feedbackStatus作为查询参数传递
  axios.put(BASE_URL + `/api/feedbacks/processing/update?feedbackStatus=${processingForm.value.status}`, processingData)
    .then(response => {
      if (response.data.state === 2001) {
        ElMessage.success('处理信息更新成功')
        // 更新本地反馈状态
        feedback.value.status = processingForm.value.status
      } else {
        ElMessage.error(response.data.msg || '更新处理信息失败')
      }
    })
    .catch(error => {
      console.error('更新处理信息失败:', error)
      ElMessage.error('更新处理信息失败: ' + (error.message || '网络错误'))
    })
}

// 添加积分
const addPoints = (points) => {
  ElMessageBox.confirm(
    `确定为用户 ${feedback.value.userName} 增加 ${points} 积分吗？`,
    '积分奖励',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      // 调用后端接口更新用户积分
      axios.put(BASE_URL + `/api/users/update/points`, null, {
        params: {
          userId: feedback.value.userId,
          points: points
        }
      })
        .then(response => {
          if (response.data.state === 2001) {
            ElMessage.success(`成功为用户 ${feedback.value.userName} 增加 ${points} 积分`);
          } else {
            ElMessage.error(response.data.msg || `为用户增加积分失败`);
          }
        })
        .catch(error => {
          console.error('更新用户积分失败:', error);
          ElMessage.error('更新用户积分失败: ' + (error.message || '网络错误'));
        });
    })
    .catch(() => {
      ElMessage.info('已取消操作');
    });
}

// 返回上一页
const goBack = () => {
  router.go(-1)
}

// 初始化数据
onMounted(() => {
  // 从路由参数获取反馈信息
  feedback.value = {
    feedbackId: route.query.feedbackId || '',
    userId: route.query.userId || '',
    userName: route.query.userName || '',
    content: route.query.content || '',
    createdAt: route.query.createdAt || '',
    status: route.query.status || 'pending'
  }

  // 获取处理信息
  getFeedbackProcessing()
})
</script>

<style scoped>
.feedback-process-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 20px;
  padding: 16px 24px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  font-weight: 600;
  color: #303133;
  font-size: 18px;
}

.feedback-card,
.processing-card,
.points-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.processing-form {
  padding: 20px 0;
}

.points-content p {
  margin-bottom: 20px;
  font-size: 16px;
  color: #606266;
}

.points-buttons {
  display: flex;
  gap: 20px;
  justify-content: center;
}

.points-buttons .el-button {
  padding: 12px 24px;
  font-size: 16px;
  border-radius: 8px;
}

:deep(.el-descriptions__label) {
  font-weight: 500;
  width: 100px !important;
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.el-textarea__inner) {
  border-radius: 6px;
}

:deep(.el-button) {
  border-radius: 6px;
  transition: all 0.3s ease;
}

:deep(.el-button:hover) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}
</style>
